package com.meilai.project.vo.business.intentionScheme;

import com.meilai.project.entity.business.intentionScheme.VGasStationComboRuleMediaTypeCount;
import io.swagger.annotations.ApiModel;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author xchen
 * @since 2022-03-12
 */
@Data
@ApiModel
public class ComboVO {
	private Long combo_id;
	private List<RuleVO> ruleList;

	@Data
	public static class RuleVO {
		private Long rule_id;
		private String rule_name;
		private List<MediaTypeCountVO> mediaType2CountList;
	}

	@Data
	public static class MediaTypeCountVO {
		private Long media_type_id;
		private String media_type_name;
		private Integer count;
	}

	public static List<ComboVO> parse(List<VGasStationComboRuleMediaTypeCount> countList) {
		List<ComboVO> result = new ArrayList<>();
		Map<Long, List<VGasStationComboRuleMediaTypeCount>> collect =
				countList.stream().collect(Collectors.groupingBy(VGasStationComboRuleMediaTypeCount::getCombo_id));
		for (Map.Entry<Long, List<VGasStationComboRuleMediaTypeCount>> entry : collect.entrySet()) {
			ComboVO comboVO = new ComboVO();
			comboVO.setCombo_id(entry.getKey());
			List<RuleVO> ruleList = new ArrayList<>();
			comboVO.setRuleList(ruleList);
			result.add(comboVO);
			List<VGasStationComboRuleMediaTypeCount> ruleItemList = entry.getValue();
			Map<Long, List<VGasStationComboRuleMediaTypeCount>> ruleListMap = ruleItemList.stream().collect(Collectors.groupingBy(VGasStationComboRuleMediaTypeCount::getCombo_rule_id));
			for (Map.Entry<Long, List<VGasStationComboRuleMediaTypeCount>> ruleEntry : ruleListMap.entrySet()) {
				RuleVO ruleVO = new RuleVO();
				ruleVO.setRule_id(ruleEntry.getKey());
				List<MediaTypeCountVO> mediaTypeCountVOList = new ArrayList<>();
				ruleVO.setMediaType2CountList(mediaTypeCountVOList);
				StringBuilder ruleName = new StringBuilder();
				for (VGasStationComboRuleMediaTypeCount typeCount : ruleEntry.getValue()) {
					MediaTypeCountVO item = new MediaTypeCountVO();
					item.setMedia_type_id(typeCount.getMedia_type_id());
					item.setMedia_type_name(typeCount.getMedia_type_name());
					item.setCount(typeCount.getCount());
					mediaTypeCountVOList.add(item);
					ruleName.append(item.getCount()).append(item.getMedia_type_name()).append("+");
				}
				ruleVO.setRule_name(ruleName.substring(0, ruleName.length() - 1));
				ruleList.add(ruleVO);
			}
		}
		return result;
	}
}
